package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.live.LiveVO;
import com.burgeon.backend.SHOP.service.AppLiveStreamingService;
import com.burgeon.backend.SHOP.service.SystemService;
import com.burgeon.backend.service.ex.ErrorDataException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class AppLiveStreamingServiceImpl implements AppLiveStreamingService {
    @Autowired
    private SystemService systemService;

    @Override
    public List<LiveVO> getLiveData(String token) {

        String accesToken = systemService.GetAccesToken(token);

        String url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + accesToken;
        String param = "{" +
                "\"start\": 0," +
                "\"limit\": 100" +
                "}";

        System.err.println(url);
        System.err.println(param);
        String str = Send(url, param);

        System.err.println(str);
        List<LiveVO> liveVOS = new ArrayList<LiveVO>();
        try {
            JSONObject jsonObject = new JSONObject(str);
            String errcode = jsonObject.getString("errcode");
            if (!"0".equals(errcode)){
                return null;
            }
            JSONArray room_info = jsonObject.getJSONArray("room_info");

            for (int i =0;i<room_info.length();i++){
                JSONObject room_info_bean = room_info.getJSONObject(i);
                LiveVO liveVO = new LiveVO();
                liveVO.setName(room_info_bean.getString("name"));
                liveVO.setCoverImg(room_info_bean.getString("cover_img").replace("http","https").replace("httpss","https"));
                liveVO.setShareImg(room_info_bean.getString("share_img").replace("http","https").replace("httpss","https"));
                liveVO.setFeedsImg(room_info_bean.getString("feeds_img").replace("http","https").replace("httpss","https"));

                liveVO.setStartTime(stampToDate(room_info_bean.getString("start_time")));
                liveVO.setEndTime(stampToDate(room_info_bean.getString("end_time")));

                liveVO.setAnchorName(room_info_bean.getString("anchor_name"));
                liveVO.setRoomid(room_info_bean.getString("roomid"));
                liveVO.setFeedsImg(room_info_bean.getString("feeds_img"));
                liveVO.setLiveStatus(room_info_bean.getString("live_status"));

                liveVOS.add(liveVO);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return liveVOS;
    }


    /*
     * 将时间戳转换为时间
     */
    private String stampToDate(String s){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return sdf.format(Long.parseLong(s)*1000);
    }

    //发送
    private String Send(String URL,String data){

        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            java.net.URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);// 设置是否允许数据写入
            connection.setDoOutput(true);// 设置是否允许参数数据输出
            connection.setConnectTimeout(5000);// 设置链接响应时间
            connection.setReadTimeout(10000);// 设置参数读取时间
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            // 提交请求
            out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);

            out.write(data);
            out.flush();
            // 读取返回参数
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                result.append(temp);
            }
        } catch (Exception e) {
            System.err.println("微信添加Tags接口错误");
            throw new ErrorDataException("微信添加Tags接口错误");
        }

        return String.valueOf(result);
    }
}
